package com.power.web.action.organization;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.power.Constants;
import com.power.model.hospital.TiHospital;
import com.power.model.user.TsSysuser;
import com.power.services.hospital.HospitalService;
import com.power.util.CharacterUtil;
import com.power.util.DateJsonValueProcessor;
import com.power.util.DateTimeUtil;
import com.power.util.RequestUtil;
import com.power.web.action.base.AbstractBaseAction;

public class OrganizationAction extends AbstractBaseAction {

	@Autowired
	@Qualifier("hospitalService")
	private HospitalService hospitalService;

	private TiHospital hospital;
	private String jsonString;
	private int flag;

	@SuppressWarnings("unchecked")
	public String buildJSONString() {
		try {
			int start = this.start;
			int limit = this.limit;
			if (limit == 0)
				limit = 20;
			String hospitalName = CharacterUtil.encode(RequestUtil.getParam(
					request, "hospitalName", ""));
			Integer pid = RequestUtil.getParam(request, "pid", -1);
			Map<String, Object> map = this.hospitalService.findAll(
					hospitalName, start, limit, pid);
			List<TiHospital> list = (List<TiHospital>) map.get("data");
			int count = new Integer(map.get("count").toString());
			StringBuffer _JSONStr = null;
			String callback = this.callback;
			_JSONStr = new StringBuffer();
			_JSONStr.append(callback).append("({\"total\":").append(count)
					.append(",\"results\":");
			JsonConfig cfg = new JsonConfig();
			cfg.registerJsonValueProcessor("inputDate",
					new DateJsonValueProcessor("yyyy-MM-dd kk:mm:ss"));
			cfg.registerJsonValueProcessor(java.util.Date.class,
					new DateJsonValueProcessor("yyyy-MM-dd"));
			cfg.registerJsonValueProcessor(java.sql.Date.class,
					new DateJsonValueProcessor("yyyy-MM-dd"));
			JSONArray jsonObject = JSONArray.fromObject(list, cfg);
			_JSONStr.append(jsonObject.toString());
			_JSONStr.append("})");
			jsonString = _JSONStr.toString();
		} catch (Exception e) {
			log.error("加载医院信息列表出错", e);
			this.jsonString = "[]";
		}
		return Constants.JSONSTRING_RESULT_NAME;
	}

	/**
	 * 根据地区筛选出单位
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String loadByDistrict() {
		this.response.reset();
		this.response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		List<TiHospital> list = new ArrayList<TiHospital>();
		try {
			out = response.getWriter();
			Integer pid = RequestUtil.getParam(this.request, "pid", -1);
			if (pid != -1) {
				Map<String, Object> map = this.hospitalService.findAll("", 0,
						1000, pid);
				list = (List<TiHospital>) map.get("data");
			}
			String callback = RequestUtil.getParam(this.request, "callback",
					"callback");
			StringBuffer _JSONStr = new StringBuffer();
			_JSONStr.append(callback).append("([");
			for (int i = 0; i < list.size(); ++i) {
				TiHospital obj = (TiHospital) list.get(i);
				_JSONStr.append("[\"").append(obj.getId()).append("\",");
				_JSONStr.append("\"").append(obj.getName()).append("\"],");
			}
			if (list.size() > 0)
				_JSONStr.deleteCharAt(_JSONStr.lastIndexOf(","));
			_JSONStr.append("])");
			this.jsonString = _JSONStr.toString();
			out.print(this.jsonString);
		} catch (Exception e) {
			log.error("加载单位出错", e);
			out.print("[]");
		}
		return null;
	}

	public String delete() throws Exception {
		String id = RequestUtil.getParam(this.request, "deleteID", "");
		String[] ids = id.split("_");
		try {
			this.response.setCharacterEncoding("UTF-8");
			for (int i = 0; i < ids.length; i++) {
				TiHospital hospital = this.hospitalService.read(new Integer(
						ids[i]));
				this.hospitalService.delete(hospital);
			}
			this.response.getWriter().print("{success:true,msg:'删除成功!'}");
		} catch (Exception e) {
			log.error("输出JSON数据错误！", e);
			this.response.getWriter().print("{failure:true,msg:'删除失败!'}");
		}
		return null;
	}

	public String saveOrUpdate() {
		this.response.reset();
		this.response.setCharacterEncoding("UTF-8");
		try {
			if (null != hospital) {
				TsSysuser user = (TsSysuser) this.session
						.get(Constants.USERINFO_KEY);
				hospital.setInputDate(DateTimeUtil.getCurrentDateTime());
				hospital.setInputMan(user.getUsername());
				hospital.setInputManId(user.getId());
				hospitalService.saveOrUpdate(hospital);
			}
			this.response.getWriter().print("{success:true,msg:'保存成功!'}");
		} catch (Exception e) {
			log.error("医院信息保存失败", e);
			try {
				this.response.getWriter().print("{success:false,msg:'保存失败!'}");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public String read() {
		int id = RequestUtil.getParam(this.request, "id", -1);
		hospital = this.hospitalService.read(new Integer(id));
		return "showhospital";
	}

	public String execute() {
		return null;
	}

	public TiHospital getHospital() {
		return hospital;
	}

	public void setHospital(TiHospital hospital) {
		this.hospital = hospital;
	}

	public String getJsonString() {
		return jsonString;
	}

	public int getFlag() {
		return flag;
	}

	public void setFlag(int flag) {
		this.flag = flag;
	}

	public void setJsonString(String jsonString) {
		this.jsonString = jsonString;
	}

}